package com.weasel.im.client;

import com.weasel.im.client.initializer.IMClientInitializer;
import com.weasel.im.common.domain.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Dylan on 2015/11/27.
 */
public class IMClientLauncher {

    private final static Logger logger = LoggerFactory.getLogger(IMClientLauncher.class);

    private Channel channel = null;
    private String host;
    private int port;

    public static IMClientLauncher listen(String _host,int _port){

        IMClientLauncher launcher = new IMClientLauncher();
        launcher.host = _host;
        launcher.port = _port;
        return launcher;
    }

    public IMClientLauncher launch(){

        final EventLoopGroup boss = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(boss)
                 .channel(NioSocketChannel.class)
                 .option(ChannelOption.SO_KEEPALIVE, true)
                 .handler(new IMClientInitializer());

        logger.info("客户端启动");

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                boss.shutdownGracefully();
                logger.info("客户端关闭");
            }
        });
        try {
            ChannelFuture future = bootstrap.connect(host, port)
                                            .sync();
            channel =  future.channel();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return this;
    }

    public void write(Message message){
        channel.writeAndFlush(message);
    }

    private IMClientLauncher(){};
}

